package cn.xiaobai.listener;

import cn.xiaobai.config.FileListenerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 程序启动加载文件监听器
 *
 * @Author yangdaji
 * @Date 2022/11/7 0007
 * @PackageName xiaobai.listener
 * @ClassName FileApplicationRunner
 */
@Slf4j
@Component
public class FileApplicationRunner implements ApplicationRunner {

    @Autowired
    private FileListenerFactory fileListenerFactory;


    @Override
    public void run(ApplicationArguments args) {
        createFileListener();
    }

    /**
     * 创建监听器
     */
    private void createFileListener() {
        FileAlterationMonitor fileAlterationMonitor = fileListenerFactory.getPushFileMonitor();
        FileAlterationMonitor pushChannelMonitor = fileListenerFactory.getPushChannelMonitor();

        startMonitor(fileAlterationMonitor);
        startMonitor(pushChannelMonitor);
    }

    /**
     * 启动监听器
     *
     * @param monitor 监听器
     */
    private void startMonitor(FileAlterationMonitor monitor) {
        try {
            // 启动监听
            monitor.start();
        } catch (Exception e) {
            log.info("监听器启动失败: {}", e.getMessage());
            try {
                monitor.stop();
            } catch (Exception ex) {
                log.info("监听器停止失败: {}", ex.getMessage());
            }
        }
    }
}
